const { sequelize } = require('../utils/sequelize');
const { v4: uuidv4 } = require('uuid');
const { HttpException } = require('../utils/http-exception')

class CourseTypeService {
    constructor() {
    }

    async findAll(){
        let data = null;
        data = await sequelize.models.CourseType.findAll();
        return data;
    }

    async saveCourseType(typeObj){
        let data = null;
        data = await sequelize.models.CourseType.create({
            categoryId: uuidv4(),
            categoryName: typeObj.categoryName
        })
        return data;
    }

    async deleteCourseType(categoryId){
        let data = null;
        let hasUse = await sequelize.models.Course.findOne({
            where: {
                categoryId: categoryId
            }
        })
        if(hasUse) throw new HttpException('还存在该分类的课程，不能删除')
        
        data = await sequelize.models.CourseType.destroy({
            where: {categoryId: categoryId}});
        return data;
    }

    async updateCourseType(obj){
        let data = null;
        let typeObj = {
            categoryName: obj.categoryName,
        }
        data = await sequelize.models.CourseType.update({...typeObj}, {
            where: {categoryId: obj.categoryId}
        })
        return data;
    }

    async getOneAttr(categoryId, attr) {
        let attrValue = '';
        let cateory = await sequelize.models.CourseType.findOne({
            attributes: [ attr ],
            where: {categoryId: categoryId}
        });
        attrValue = cateory.getDataValue(attr)
        return attrValue;
    }
}



module.exports = new CourseTypeService();